package org.jpass.dc.business.project.dao;

import java.util.List;

import org.jpass.dc.business.project.bean.CProject;
import org.jpass.dc.common.bean.Page;
import org.jpass.dc.common.dao.GenericDao;

public class ProjectDao extends GenericDao<CProject> {

	public ProjectDao() {
		super(CProject.class);
	}

	/**
	 * 根据条件查询
	 * @param userId
	 * @param projectName
	 * @return
	 */
	public CProject queryByUserIdAndProjectName(String userId, String projectName) {
		StringBuffer searchHql = new StringBuffer("from CProject as cp where")
				.append(" cp.user.id = '").append(userId)
				.append("' and cp.projectName = '").append(projectName)
				.append("'");
		
		return this.query(searchHql.toString());
	}
	
	/**
	 *  通过用户id取得用户建立的项目
	 * @param userId
	 * @return
	 */
	public List<CProject> queryForClosedProjectsByUserId(String userId) {
		return this.queryForList(
				"select new CProject(p.id, p.projectName, p.projectType, p.createdDate) from CProject as p where p.user.id=? and p.status=1", 
				new Object[] {userId}, 
				null);
	}
	
	public List<CProject> queryForClosedProjectsByUserId(String userId, Page page) {
		String countHql = "select count(*) from CProject as p where p.user.id=? and p.status=0";
		String searchHql = "select new CProject(p.id, p.projectName, p.projectType, p.createdDate, p.status) from CProject as p where p.user.id=? and p.status=0";
		return this.queryForList(
				countHql,
				searchHql,
				new Object[] {userId}, 
				page);
	}
	
	public boolean updateProjectStatus(String userId, String[] projectIds, boolean status) {
		int flag = 0;
		String idStr = transformArrayToString(projectIds);
		String hql = "update CProject as p set p.status=? where p.user.id=? and p.id in ("+ idStr + ")";
		
		flag = this.executeUpdate(hql, new Object[] {status, userId});
		
		if (flag <= 0) {
			return false;
		}
		
		return true;
	}
	
	public String transformArrayToString(String[] arry) {
		StringBuffer strbuf = new StringBuffer();
		for (String str : arry) {
			strbuf.append("\'").append(str).append("\',");
		}
		
		return strbuf.toString().substring(0, strbuf.toString().length() - 1);
	}
}
